package com.ecp.commons.serialization;

import java.io.Serializable;

import com.ecp.commons.annotation.VariantType;

public class Variant implements Serializable {
	private static final long	serialVersionUID	= 1L;

	private String				value				= null;
	private VariantType			type				= VariantType.STRING;
	private boolean				nullable			= true;
	private int					length				= 0;
	private String				alias				= null;
	private boolean				pk					= false;
	private boolean				persistent			= true;
	private boolean				serialize			= true;

	public Variant() {
	}

	// 构造函数也可以用位标记，如 FLAG_NOT_NULL|FLAG_PK
	public Variant(VariantType type, boolean nullable, int length, String alias, boolean pk, boolean persistent,
			boolean serialize) {
		//this.value = value;	// 只初始化属性，不初始化值。属性一旦初始化，暂不让修改
		this.type = type;
		this.nullable = nullable;
		this.length = length;
		this.alias = alias;
		this.pk = pk;
		this.persistent = persistent;
		this.serialize = serialize;
	}

	public Variant setType(VariantType type) {
		this.type = type;
		return this;
	}

	public Variant setNullable(boolean nullable) {
		this.nullable = nullable;
		return this;
	}

	public Variant setLength(int length) {
		this.length = length;
		return this;
	}

	public Variant setAlias(String alias) {
		this.alias = alias;
		return this;
	}

	public Variant setPk(boolean pk) {
		this.pk = pk;
		return this;
	}

	public Variant setPersistent(boolean persistent) {
		this.persistent = persistent;
		return this;
	}

	public Variant setSerialize(boolean serialize) {
		this.serialize = serialize;
		return this;
	}

	/*
	static public Variant newIntVariant(boolean nullable, boolean pk) {
		Variant var = new Variant();
		var.type = 0;
		var.nullable = nullable;
		var.pk = pk;
		return var;
	}
	*/

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		if (value != null && value.length() == 0 && type != VariantType.STRING) {
			if (nullable) {
				value = null;
			} else if (type == VariantType.DATETIME){
				value = "2000-01-01 00:00:00";
			} else {
				value = "0";
			}
		}
		this.value = value;
	}

	public VariantType getType() {
		return type;
	}

	public boolean isNullable() {
		return nullable;
	}

	public int getLength() {
		return length;
	}

	public String getAlias() {
		return alias;
	}

	public boolean isPk() {
		return pk;
	}

	public boolean isPersistent() {
		return persistent;
	}

	public boolean isSerialize() {
		return serialize;
	}

	@Override
	public String toString() {
		return (value != null) ? value : "null";
	}
}
